package com.ruoyi.mobile.annotation.support;

import com.ruoyi.mobile.annotation.WxLoginUser;
import com.ruoyi.mobile.service.UserTokenManager;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver
{
    public static final String LOGIN_TOKEN_KEY = "X-Mall-Token";

    @Override
    public boolean supportsParameter(MethodParameter parameter)
    {
        return parameter.getParameterType().isAssignableFrom(Long.class) && parameter.hasParameterAnnotation(WxLoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request, WebDataBinderFactory factory) throws Exception
    {
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty())
        {
            return null;
        }

        return UserTokenManager.getUserId(token);
    }
}
